package org.jeecg.modules.oauth.xkwoauth.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author lwz
 * @description http发送https请求工具类
 */
public class HttpsUtils {
	private static final Logger logger = LoggerFactory.getLogger(HttpsUtils.class);

	/**
	 * @author: lwz
	 * @description:
	 * @param: [localUrl]
	 * @return: java.lang.String 服务器返回的json字符串
	 * @date: 11:35 2018/1/11
	 */
	public static String httpPost(String localUrl) throws Exception{
        URL url = new URL(localUrl);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        X509TrustManager xtm = getInstance();
        TrustManager[] tm = { xtm };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tm, null);
        con.setSSLSocketFactory(ctx.getSocketFactory());
        con.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        }); 
        int resCode;
        try {
        	resCode=con.getResponseCode();
		} catch (Exception e) {
			logger.error(e.toString());
        	throw new Exception("DNS解析失败，未找到服务地址");
        }
        //服务服务地址可以联通，会返回相应的code码
        if(resCode==200){
        	InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream());
        	//读取服务器的响应内容并显示
        	String result="";
        	int respInt = inputStreamReader.read();
        	while( respInt != -1){
        		result+=(char)respInt;
        		respInt=inputStreamReader.read();
        	}
        	return result;
        }else{
        	throw new Exception("服务地址无响应,异常码："+con.getResponseCode());
        }
	}

	/**
     * @author: lwz
     * @description: 获取 X509TrustManager 实例
     * @param: []
     * @return: javax.net.ssl.X509TrustManager
     * @date: 11:38 2018/1/11
     */
	private static X509TrustManager getInstance(){
	    return new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // TODO Auto-generated method stub
                return null;
            }
            public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                    throws CertificateException {
                // TODO Auto-generated method stub

            }
            public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                    throws CertificateException {
                // TODO Auto-generated method stub

            }
        };
    }
}